package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.ExpressPackage;
import com.ruoyi.system.service.IExpressPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 快递登记Controller
 */
@RestController
@RequestMapping("/api/express")
public class ExpressPackageController extends BaseController {

    @Autowired
    private IExpressPackageService expressPackageService;

    /**
     * 查询快递登记列表
     */
    @PreAuthorize("@ss.hasPermi('system:express:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExpressPackage expressPackage) {
        startPage();
        List<ExpressPackage> list = expressPackageService.selectExpressPackageList(expressPackage);
        return getDataTable(list);
    }

    /**
     * 导出快递登记列表
     */
    @PreAuthorize("@ss.hasPermi('system:express:export')")
    @Log(title = "快递登记", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ExpressPackage expressPackage) {
        List<ExpressPackage> list = expressPackageService.selectExpressPackageList(expressPackage);
        ExcelUtil<ExpressPackage> util = new ExcelUtil<>(ExpressPackage.class);
        util.exportExcel(response, list, "快递登记数据");
    }

    /**
     * 获取快递登记详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:express:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(expressPackageService.selectExpressPackageById(id));
    }

    /**
     * 新增快递登记
     */
    @PreAuthorize("@ss.hasPermi('system:express:add')")
    @Log(title = "快递登记", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExpressPackage expressPackage) {
        return toAjax(expressPackageService.insertExpressPackage(expressPackage));
    }

    /**
     * 修改快递登记
     */
    @PreAuthorize("@ss.hasPermi('system:express:edit')")
    @Log(title = "快递登记", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExpressPackage expressPackage) {
        return toAjax(expressPackageService.updateExpressPackage(expressPackage));
    }

    /**
     * 删除快递登记
     */
    @PreAuthorize("@ss.hasPermi('system:express:remove')")
    @Log(title = "快递登记", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(expressPackageService.deleteExpressPackageByIds(ids));
    }

    /**
     * 小程序 - 登记快递
     */
    @Anonymous
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody ExpressPackage expressPackage) {
        LoginUser loginUser = getRequiredLoginUser();
        expressPackage.setUserId(loginUser.getUserId());
        String displayName = loginUser.getUser() != null && StringUtils.isNotEmpty(loginUser.getUser().getNickName())
            ? loginUser.getUser().getNickName()
            : loginUser.getUsername();
        expressPackage.setUserName(displayName);
        expressPackage.setCreateBy(loginUser.getUsername());
        int rows = expressPackageService.insertExpressPackage(expressPackage);
        if (rows > 0) {
            ExpressPackage saved = expressPackageService.selectExpressPackageById(expressPackage.getId());
            AjaxResult result = AjaxResult.success("登记成功");
            result.put("serial", saved.getSerial());
            return result;
        }
        return error("登记失败，请重试");
    }

    /**
     * 小程序 - 我的快递列表
     */
    @Anonymous
    @GetMapping("/my/list")
    public TableDataInfo myList(ExpressPackage expressPackage) {
        LoginUser loginUser = getRequiredLoginUser();
        expressPackage.setUserId(loginUser.getUserId());
        startPage();
        List<ExpressPackage> list = expressPackageService.selectExpressPackageList(expressPackage);
        return getDataTable(list);
    }

    /**
     * 快递送达确认
     */
    @PreAuthorize("@ss.hasPermi('system:express:deliver')")
    @Log(title = "快递送达", businessType = BusinessType.UPDATE)
    @PutMapping("/deliver/{id}")
    public AjaxResult deliver(@PathVariable("id") Long id) {
        ExpressPackage expressPackage = new ExpressPackage();
        expressPackage.setId(id);
        expressPackage.setStatus("delivered");
        expressPackage.setDeliverBy(getUsername());
        expressPackage.setDeliverTime(DateUtils.getNowDate());
        expressPackage.setUpdateBy(getUsername());
        return toAjax(expressPackageService.updateExpressPackage(expressPackage));
    }

    private LoginUser getRequiredLoginUser() {
        try {
            return getLoginUser();
        } catch (Exception e) {
            throw new ServiceException("登录状态已过期，请重新登录");
        }
    }
}

